<template>
  <div class="page">

    <van-loading v-if="loading" class="loading" />


    <van-nav-bar left-arrow @click-left="onClickLeft"
      :style="{ background: navBarBackground, borderBottom: navBarBorder, boxShadow: navBarBoxShadow }" fixed>
      <template #right>
        <van-icon name="share-o" size="18" @click="onClickRight" color="#fff" />
      </template>
      <template #title>
        <!-- {{ comicDetail.title }} -->
        <span style="color: #fff;"> {{ dynamicTitle }} </span>
      </template>
    </van-nav-bar>

    <div class="banner">
      <img :src="getProxyImageUrl(comicDetail.bigpic)" :alt="comicDetail.title" class="cover" v-if="comicDetail.bigpic">
      <div class="brief">
        <div class="title-urge" v-if="comicDetail">
          <div class="title">{{ comicDetail.title }}</div>
          <div class="urge"> <van-icon name="bulb-o" size="20"></van-icon> {{ comicDetail.urge_num }}次 <button
              type="button" class="button">催更</button></div>
        </div>
        <div class="author-tag">
          <div class="author">{{ comicDetail.author }}</div>
          <div class="tag">{{ comicDetail.tag }}</div>
        </div>

      </div>
    </div>

    <div class="profile" v-if="comicDetail.info">
      <div class="info">
        <van-text-ellipsis :content="comicDetail.info" rows="4" expand-text="展开" collapse-text="收起" :position="end" />
      </div>
      <div class="three">
        <div class="fav" v-if="comicDetail.num_fav">
          <p> {{ comicDetail.num_fav }} </p>
          <p>收藏数</p>
        </div>
        <div class="love" v-if="comicDetail.num_love">
          <p> {{ comicDetail.num_love }}</p>
          <p> 点赞数 </p>
        </div>
        <div class="look" v-if="comicDetail.num_look">
          <p>{{ comicDetail.num_look }}</p>
          <p> 人气数</p>
        </div>
      </div>
    </div>

    <!-- 漫画全集 -->
    <div class="catalog" v-if="chapters">
      <div class="catalog-header">
        <div class="header">漫画全集</div>
        <div class="directory" @click="popUpDirectory">目录<van-icon name="arrow" /></div>
      </div>
      <div class="catalog-content">

        <div class="more" @click="popUpDirectory">
          <van-icon name="back-top" class="back-top" />
          <p>查看更多</p>
        </div>
        <ul>
          <li v-for="(chapter, index) in chapters" :key="chapter.id" class="chapter" @click="gotoComicChapter(index)">
            <img :src="getProxyImageUrl(chapter.cover)" :alt="chapter.name" class="cover">
            <p class="name">{{ chapter.name }}</p>
          </li>
        </ul>
      </div>
    </div>
    <div class="hot-comments" v-if="hotComments">
      <div class="comment-heder">
        <div class="header">热门评论</div>
        <div class="push-comment"><van-icon name="comment-o" />发评论</div>
      </div>
      <ul class="comment-list">
        <li class="comment-item" v-for="comment in hotComments" :key="comment.id">
          <img :src="getProxyImageUrl(comment.uhead)" :alt="comment.uname" class="avatar">
          <div class="name-content">
            <div class="name">{{ comment.uname }}</div>
            <div class="content">{{ comment.content }}</div>
            <div class="date-like-reply">
              <div class="date">{{ formatTimeAgo(comment.lastmodified) }}</div>
              <div class="like-reply">
                <span class="like"><van-icon name="good-job-o" />{{ comment.like_count }} </span>
                <span class="reply">
                  <van-icon name="chat-o" />{{ comment.reply_count }}
                </span>
              </div>
            </div>
          </div>
        </li>
      </ul>
      <div class="more-comments" @click="router.push({ path: `/comments/${route.params.id}`, })">查看全部精彩评论</div>
    </div>



    <div class="recommends" v-if="relatedComics">
      <div class="recommend-header">根据你喜欢个性化推荐</div>
      <ul class="recommend-content">
        <li v-for="comic in relatedComics" :key="comic.id" class="recommend-item" @click="onClickRecommend(comic.id)">
          <img :src="getProxyImageUrl(comic.pic)" :alt="comic.title" class="recommend-img" />
          <p class="title">{{ comic.title }}</p>
        </li>
      </ul>
    </div>

    <van-popup v-model:show="showDirectory" round position="bottom" closeable close-icon-position="top-right"
      close-on-click-overlay="false" class="pop-up-directory">
      <div class="container">
        <div class="directory-title">目录</div>
        <span>全部章节</span>
        <div class="sort" @click="toggleSortOrder">
          <div class="icon">
            <van-icon name="arrow-up" class="up" :color="sortOrder === 'desc' ? '#ff0000' : '#a0a0a0'" /> <!-- 倒序  -->
            <van-icon name="arrow-down" class="down" :color="sortOrder === 'asc' ? '#ff0000' : '#a0a0a0'" />
            <!-- 正序 -->
          </div>
          <div class="text">
            <template v-if="sortOrder === 'asc'">
              <span> 章节正序 </span>
            </template>
            <template v-else>
              <span> 章节倒序 </span>
            </template>
          </div>
        </div>
      </div>
      <ul>
        <li class="chapter-item" v-for="(chapter, index) in sortedChapters" :key="chapter.id"
          @click="gotoComicChapter(index)">
          <img class="chapter-cover" :src="getProxyImageUrl(chapter.cover)" :alt="chapter.name" />
          <div class="name-date">
            <div class="name">{{ chapter.name }}</div>
            <div class="date">
              <span>{{ timestampToDate(chapter.createtime) }}</span>
              <span><van-icon name="like-o" /> {{ chapter.num_love }}</span>
            </div>
          </div>
        </li>
      </ul>
    </van-popup>

    <footer>
      <div class="collect">
        <van-icon name="star-o" /> <span> 收藏漫画 </span>
      </div>
      <van-button type="primary" round size="small" color="#ff0000" @click="gotoComicDetail">
        <template v-if="openComicId > 0 && currentChapterIndex > 0">
          续看{{ currentChapterIndex }}话
        </template>
        <template v-else>开始查看</template>
      </van-button>
    </footer>
  </div>

</template>




<script setup>
import { getProxyImageUrl, timestampToDate } from "@/util/index.js"
import { getComicDetail, getComicChapters, getRelatedComics, getCommentCount, getHotComments } from '@/api/index.js';
import { useRouter, useRoute } from 'vue-router';
import { computed, onMounted, ref, onUnmounted, watch } from 'vue';
import { useStore } from "@/stores/index.js";
const store = useStore();

const router = useRouter();
const route = useRoute();

const comicId = computed(() => route.params.id);


const comicDetail = ref({});
const showDirectory = ref(false); // 目录弹窗状态

// 动态标题
const dynamicTitle = ref('');

// 导航栏背景颜色
const navBarBackground = ref('transparent');
// 导航栏边框样式
const navBarBorder = ref('none!important'); // 初始边框无
const navBarBoxShadow = ref('none!important'); // 初始无阴影


const loading = ref(true); // 加载状态

const chapters = ref([])

const hotComments = ref([])

const relatedComics = ref([])

const sortOrder = ref("asc"); // 默认升序

const sortedChapters = computed(() => {
  return [...chapters.value].sort((a, b) => {
    if (sortOrder.value === "asc") {
      return a.id - b.id; // 升序
    } else if (sortOrder.value === "desc") {
      return b.id - a.id; // 降序
    }
  });
});

const currentChapterIndex = computed(() => store.currentChapterIndex)
const openComicId = computed(() => store.openComicId)


const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === "asc" ? "desc" : "asc";
};

// 页面滚动事件处理函数
const handleScroll = () => {
  const banner = document.querySelector('.banner');
  if (!banner) return;

  // 获取 banner 的底部位置相对于视口的位置
  const bannerBottom = banner.getBoundingClientRect().bottom;

  // 当 banner 滑出视口时，更新动态标题和导航栏背景
  if (bannerBottom <= 0) {
    dynamicTitle.value = comicDetail.value.title;
    navBarBackground.value = 'rgba(60, 40, 20, 0.9)'; // 深褐色背景
  }

  // 当 banner 回到视口时，清空动态标题并恢复透明背景
  if (bannerBottom > 0) {
    dynamicTitle.value = '';
    navBarBackground.value = 'transparent';
  }
};


//打开目录
const popUpDirectory = () => {
  showDirectory.value = true;
}

// 跳转到漫画某个章节
const gotoComicChapter = (index) => {
  // console.log("当前索引", index);
  if (sortOrder.value === "asc") {
    // 设置要打开的章节索引
    store.setCurrentChapterIndex(index);
  } else if (sortOrder.value === "desc") {
    store.setCurrentChapterIndex(sortedChapters.value.length - index);
  }
  // 跳转到漫画详情页
  router.push({ path: `/comicDetail/${comicId.value}` });
}


const onClickRecommend = (id) => {
  console.log("comic.id", id);
  router.push({ path: `/comicCover/${id}` });
}

watch(comicId, async (newVal) => {
  loading.value = true;
  window.scrollTo({ top: 0, behavior: 'smooth' }); // 回到顶部
  //加载漫画详情内容
  const res = await getComicDetail(newVal);
  comicDetail.value = res.data;
  // 加载当前漫画章节列表
  const resChapters = await getComicChapters(newVal)
  chapters.value = resChapters.data;
  // 加载热门评论列表
  const resComments = await getHotComments(newVal)
  hotComments.value = resComments.data;
  // 加载相关漫画列表
  const resRelated = await getRelatedComics(newVal)
  relatedComics.value = resRelated.data;
  loading.value = false;

})



onMounted(async () => {
  loading.value = true;
  window.addEventListener('scroll', handleScroll);
  //加载漫画详情内容
  const res = await getComicDetail(comicId.value);
  store.setOpenComicId(comicId.value)
  comicDetail.value = res.data;
  // 加载当前漫画章节列表
  const resChapters = await getComicChapters(comicId.value)
  chapters.value = resChapters.data;
  // 加载热门评论列表
  const resComments = await getHotComments(comicId.value)
  hotComments.value = resComments.data;
  // 加载相关漫画列表
  const resRelated = await getRelatedComics(comicId.value)
  relatedComics.value = resRelated.data;

  loading.value = false;

})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});
const onClickLeft = () => {
  router.go(-1)
}

const onClickRight = () => {
  //打开分享组件
};

const gotoComicDetail = () => {
  // store.setCurrentChapterIndex(0);
  router.push({ path: `/comicDetail/${comicId.value}` })


}
function formatTimeAgo (timestamp) {
  // 当前时间
  const now = Date.now();
  // 计算时间差（以毫秒为单位）
  const diff = now - timestamp;

  // 定义时间单位（毫秒）
  const minute = 60 * 1000; // 1 分钟 = 60,000 毫秒
  const hour = 60 * minute; // 1 小时 = 3,600,000 毫秒
  const day = 24 * hour; // 1 天 = 86,400,000 毫秒
  const month = 30 * day; // 1 月 ≈ 30 天
  const year = 365 * day; // 1 年 ≈ 365 天

  if (diff < minute) {
    return '刚刚';
  } else if (diff < hour) {
    const minutes = Math.floor(diff / minute);
    return `${minutes}分钟前`;
  } else if (diff < day) {
    const hours = Math.floor(diff / hour);
    return `${hours}小时前`;
  } else if (diff < month) {
    const days = Math.floor(diff / day);
    return `${days}天前`;
  } else if (diff < year) {
    const months = Math.floor(diff / month);
    return `${months}月前`;
  } else {
    const years = Math.floor(diff / year);
    return `${years}年前`;
  }
}




</script>



<style scoped>
.page {
  position: relative;
  width: 100vw;
  height: auto;
}

.loading {

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

}

:deep(.van-icon-arrow-left) {
  color: #fff;
}



.banner {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
  background-color: #fff;
  /* margin-top: 50px; */
}

.banner .cover {
  object-fit: cover;
  width: 100%;
  height: 200px;
  background-color: #fff;
}

.brief {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  color: #fff;
  padding: 10px;
  background: rgba(0, 0, 0, 0.6);
  z-index: 2;
  overflow: hidden;
  /* 防止阴影溢出 */
}

.brief::after {
  content: '';
  position: absolute;
  bottom: -5px;
  /* 调整位置以实现向内偏移 */
  left: 0;
  right: 0;
  height: 5px;
  /* 边框高度 */
  background: #000;
  /* 边框颜色 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
  /* 阴影效果 */
}


.title-urge,
.author-tag {
  margin-top: 5px;
  display: flex;
  align-items: center;
  justify-content: space-between;

}

.title-urge .title {
  font-size: 16px;
  font-weight: bold;
}

.urge,
.author,
.tag {
  font-size: 12px;
}


.button {
  background-color: #f1f1f1;
  border: 0;
  border-radius: 10px;
  width: 50px;
  height: 20px;
  color: #000;
}


.profile {
  padding: 12px;

  background-color: #fff;

}

:deep(.van-text-ellipsis) {
  font-size: 14px;
  line-height: 2;
  color: #222
}

:deep(.van-text-ellipsis__action) {
  color: #222
}

.three {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
  text-align: center;
  padding: 0;
  margin-top: 20px;
}

.three p {
  margin: 0
}

.three>div:not(:last-child) {
  border-right: 1px solid #f0f0f0;
  /* 添加竖线 */
}

.three>div p:nth-child(1) {
  color: #ff0000;
}

.three>div p:nth-child(2) {
  margin-top: 10px;
  font-size: 14px;
}



.catalog {
  background-color: #fff;
  margin-top: 10px;
  padding: 10px;
}

.catalog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header {
  font-size: 16px;
  font-weight: bold;
}

.directory {
  font-size: 12px;
}

.catalog-content {
  margin-top: 10px;
  display: flex;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: stretch;
  overflow-x: auto;
  scrollbar-width: none;
  overflow-x: overlay;
}

.catalog-content::-webkit-scrollbar {
  display: none;
}



.catalog-content ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
}

.catalog-content .chapter {
  width: 100%;
  height: auto;
  margin: 0 5px;
  text-align: left;

}

.catalog-content .chapter .cover {
  width: 120px;
  height: auto;
  object-fit: cover;
  border-radius: 5px;

}

.chapter p {
  margin: 5px 0 0 0;
  padding: 0;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 120px;

}





.back-top {
  transform: rotate(-90deg);
}

.more {

  text-align: center;
  display: flex;
  flex-direction: column;
  /* 确保图标和文字垂直排列 */
  justify-content: center;
  /* 垂直居中 */
  align-items: center;
  /* 水平居中 */
  margin-right: 10px;
}

.more p {
  margin: 5px 0 0 0;
  /* 调整上下间距 */
  font-size: 12px;
  white-space: nowrap;
  /* 禁止换行 */
}


.hot-comments {
  background-color: #fff;
  padding: 10px;
}

.hot-comments .comment-heder {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;

}

.comment-heder.header {
  font-size: 16px;

}

.comment-heder .push-comment {
  font-size: 14px;
}

.comment-list {
  list-style: none;
  margin: 0;
  padding: 0;

}

.comment-item {

  display: flex;
  align-items: flex-start;
  gap: 10px;
  border-bottom: 0.5px solid #f0f0f0;
  padding: 10px 0;
}

.comment-item .avatar {
  width: 20px;
  height: 20px;
  border-radius: 50%;

}

.comment-item .name-content {
  font-size: 13px;
  width: 100%;
  overflow: hidden;
  /* 防止内容溢出 */
}

.name-content .name {
  margin-bottom: 10px;


}


.name-content .content {
  font-size: 14px;
  width: 100%;
  margin-bottom: 5px;
  word-break: break-all;
  /* 添加长文本换行 */
}


.date-like-reply {
  display: flex;
  align-items: center;
  justify-content: space-between;

}


.like {
  margin-right: 10px;
}

.more-comments {
  text-align: center;
  font-size: 13px;
  margin-top: 10px;
}


.recommends {
  background-color: #fff;
  padding: 10px;
  margin-bottom: 60px;
}

.recommend-header {
  font-size: 16px;
  font-weight: bold;
}

.recommend-content {
  list-style: none;
  margin: 0;
  padding: 10px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;

}


.recommend-item {
  flex: 0 1 calc((100% - 20px) / 3);
  /* 每行 3 个元素，减去间距  3个元素10gap+10gap  再平均分3份 */
  box-sizing: border-box;
  /* 确保 padding 和 border 不会影响宽度 */
  background-color: #fff;
  text-align: center;
  padding: 0px;
  overflow: hidden;
}

.recommend-img {
  border-radius: 5px;
  object-fit: cover;
  width: 100%;
  height: 150px;
  display: block;
}

.recommend-item .title {
  margin: 0;
  text-align: left;
  font-size: 14px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 100%;
}



footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  margin-top: 10px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  padding: 10px;
  border-top: 0.5px solid #f0f0f0;
  box-sizing: border-box;
}

.collect {
  margin-left: 30px;
}

:deep(.van-button) {
  width: 180px;
}

.pop-up-directory {
  /* display: none; */
  padding: 10px;

}

.container {
  text-align: center;
  margin-bottom: 20px;
  margin-top: 50px;
  overflow: hidden;
  box-sizing: border-box;
}

.pop-up-directory ul {
  box-sizing: border-box;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
  -ms-overflow-style: none;
  /* 隐藏滚动条（IE 和 Edge） */
  scrollbar-width: none;
  overflow-y: scroll;
  /* 隐藏滚动条（Firefox） */
}

.pop-up-directory ul::-webkit-scrollbar {
  display: none;
  /* 隐藏滚动条（Webkit 浏览器，如 Chrome 和 Safari） */
}






.directory-title {
  text-align: center;

}

.container span {
  float: left;
}

.container .sort {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  cursor: pointer;
}



.chapter-item {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 5px 0;
  gap: 10px;

}

.chapter-item .chapter-cover {
  width: 100px;
  height: auto;
  object-fit: cover;
  border-radius: 5px;
}

.chapter-item .name-date {
  width: 100%;
  font-size: 14px;
}


.chapter-item .name {
  margin-bottom: 10px;
}


.chapter-item .date {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
